local getmetatable = getmetatable
local setmetatable = setmetatable
local module = module
local require = require
local type = type
local io = io
local assert = assert
local print = print
local string = string
local pcall = pcall


module('fit.LogWatcher')
_VERSION='0.2'

local Fixture = require('fit.Fixture')


-- Opens the log file
local function open(self, logFile)
    self.logFile = logFile
    self.logHandle = assert(io.open(self.logFile), "r")
    self.logHandle:seek("end")
end

-- Looks for a matching line after the current position
local function look(self, pattern)
    line = self.logHandle:read("*line")
    while line ~= nil do
        if string.find(line, pattern) ~= nil then
            return line
        else
            line = self.logHandle:read("*line")
        end
    end

    return line
end

-- Returns the next line
local function next(self, pattern)
    return self.logHandle:read("*line")
end

-- Overloading the check function so that we can add the matching line to
-- output, as well as the usual green colouring
local function check(self, cell, func)
    if func == nil or type(func) ~= "function" then
        self:errorCell(cell, "Function DNE")
    end

    pattern = cell:text()
    status, result = pcall(func, self, pattern)
    if status then
        if type(result) == "string" then
            if string.find(result, pattern) ~= nil then
                cell:addToBody("<hr />" .. self.escape(result) ..
                        self.label("matched"))
                self:right(cell)
            else
                self:wrong(cell, result)
            end
        elseif type(result) == "nil" then
            self:wrong(cell, "read returned nil, end of file?")
        else
            self:wrong(cell, result)
        end
    else
        self:exception(cell, result)
    end
end

-- Constructor
do
    local logWatcher = Fixture()

    function __call()
        logWatcher.open = open
        logWatcher.look = look
        logWatcher.next = next
        logWatcher.check = check

        return logWatcher
    end
end

setmetatable(_M, _M)
